<?php

namespace scripts;

use QYS\Protocol\Response;
use QYS\Protocol\Request;
use QYS\Db\Mysql;
use QYS\Db\Mongo;
use QYS\Log\Log;
use QYS\Db\Redis;
use globalunit\utils\Config;
use globalunit\utils\JWTUtil;
use globalunit\utils\RndName;
use globalunit\utils\Utils;
use globalunit\utils\KeysUtil;
use QYS\Core\Config as QYSConfig;
use globalunit\utils\MyLocker;
use QYS\third\Crypto\XXTEA;
use globalunit\utils\GenID;
use globalunit\utils\CoroutineCurl;
use Carbon\Carbon;
use globalunit\model\AdvBaseConfigModel;
use globalunit\model\MsgModel; //消息
use globalunit\model\Web3DModel;
use globalunit\model\AdvModel;
use globalunit\model\AdvChildModel;
use globalunit\model\GameConfigModel;
use globalunit\model\HallConfigModel;
use globalunit\model\MsgLogModel;
use globalunit\model\NoticeConfigModel;
use globalunit\model\ShareConfigModel;
use globalunit\model\SpaceBaseConfigModel;
use globalunit\model\SpaceConfigModel;
use globalunit\model\SponsorConfigModel;
use globalunit\model\WayConfigModel;


function get_name_by_id($id, $spaces)
{
    foreach ($spaces as $k => $v) {
        if ($id == $v["id"]) {
            return $v["name"];
        }
    }
    return "未定义";
}
class CMDADMIN
{

    public static function getSpaces($request, $response, $rediscli)
    {
        $m = new SpaceBaseConfigModel();
        $spaces = $m->order("id asc")->select();
        foreach ($spaces as $key => $value) {
            $spaces[$key]["space_id"] =  $value["id"];
        }
        return ['errcode' => 0, "data" => ["spaces" => $spaces]];
    }

    public static function getAdvConfigs($request, $response, $rediscli)
    {
        $space_id = $request->getInt("space_id");
        $m = new AdvBaseConfigModel();
        $advs = $m->where("space_id = {$space_id}")->order("pos asc")->select();
        return ['errcode' => 0, "data" => ["advs" => $advs]];
    }

    public static function createapp($request, $response, $rediscli)
    {
        $user_id = $request->getString("user_id");
        $organize_id = $request->getString("organize_id");
        $pfid = $request->getString("pfid");
        if (!isset($user_id) || !isset($organize_id) || !isset($pfid)) {
            return ["errcode" => 401];
        }

        $raw = $request->getRequest()->rawContent();
        $post = json_decode($raw, true);
        Log::var_dump(["post" => $post]);
        if (!isset($post['name']) || !isset($post['start_time']) || !isset($post['end_time']) || !isset($post['description']) || !isset($post['img1']) || !isset($post['img2'])) {
            return ["errcode" => 10001];
        }

        if (!isset($post["space"])) {
            return ["errcode" => 10001];
        }

        if (!isset($post["way"])) {
            return ["errcode" => 10001];
        }

        $model = new Web3DModel();
        $ok = $model->get("pfid = '{$pfid}' and organize_id = '{$organize_id}'");
        if ($ok) {
            return ['errcode' => 10002, "errmsg" => "请勿重复创建作品"];
        }

        $mysql = Mysql::getInstance("mysql1");
        $mysql->query("start transaction");
        try {

            $model = new Web3DModel();
            $model->pfid = $pfid;
            $model->organize_id = $organize_id;
            $model->name = $post['name'];
            $model->description = $post['description'];
            $model->luck_draw_url = $post['luck_draw_url'] ?? "";
            $model->start_time = $post['start_time'];
            $model->end_time = $post['end_time'];
            $model->img1 = $post['img1'];
            $model->img2 = $post['img2'];
            $ok = $model->insert();
            // Log::var_dump(["sql" => $model->getLastSql()]);
            if (!$ok) {
                throw new \Exception("err Web3DModel insert sql=" . $model->getLastSql());
            }
            $wid = $model->id;
            $space = $post["space"];
            foreach ($space as $k => $v) {
                $s = new SpaceConfigModel();
                $s->wid = $wid;
                $s->space_id = $v["space_id"];
                $s->name = $v["name"];
                $s->description = $v["description"];
                $s->img = $v["img"];
                $s->status = $v["status"];
                $ok = $s->insert();
                // Log::var_dump(["sql" => $model->getLastSql()]);
                if (!$ok) {
                    throw new \Exception("err SpaceConfigModel insert sql =" . $model->getLastSql());
                }
            }
            $way = $post["way"];
            foreach ($way as $k => $v) {
                $s = new WayConfigModel();
                $s->wid = $wid;
                $s->sort = $v["sort"];
                $s->space_id = $v["space_id"];
                $ok = $s->insert();
                // Log::var_dump(["sql" => $model->getLastSql()]);
                if (!$ok) {
                    throw new \Exception("err SpaceConfigModel insert sql =" . $model->getLastSql());
                }
            }

            //TODO:请求兔展接口 创建作品 获取appid
            $debug = QYSConfig::get("debug");
            $cookie = $request->getRequest()->header["authorization"];
            if(!$debug){
                $cookie = $request->getRequest()->cookie;
                $strs = [];
                foreach ($cookie as $key => $value) {
                    array_push($strs, $key."=".$value);
                }

                $cookie = implode(";", $strs);
            }

            $url = QYSConfig::get("app_url");
            $body = [
                "userId" => $user_id,
                "orgId" => $organize_id,
                "pfid" => $pfid,
                "appTitle" => $post["name"],
                "originAppUrl" => "http://web3dfe.rabbitpre.com/web/index.html",
                "shareDesc" => $post["description"],
                "importType" => 1,
                "subType" => 1,
                "contentType" => "showPage"
            ];
            $res = CoroutineCurl::post($url, "/api/workbench/marketing/xapp/edit", json_encode($body), $cookie);
            if (empty($res)) {
                throw new \Exception("curl xapp edit fail");
            }
            if (!$res["success"]) {
                throw new \Exception("curl xapp edit fail");
            }
            $model = new Web3DModel();
            $ok = $model->get("id = {$wid}");
            if (!$ok) {
                throw new \Exception("err Web3DModel get sql =" . $model->getLastSql());
            }
            $model->appid = $res["data"]["xappId"];
            $model->url = "http://web3dfe.rabbitpre.com/web/index.html?appid=" . $res["data"]["xappId"];
            $ok = $model->save();
            if (!$ok) {
                throw new \Exception("err Web3DModel save sql =" . $model->getLastSql());
            }

            $mysql->commit();
        } catch (\Exception $e) {
            $mysql->rollback();
            Log::var_dump(["Exception" => $e->getMessage()]);
            return ['errcode' => 10009];
        }

        $model = new Web3DModel();
        $model->get("pfid = '{$pfid}' and organize_id = '{$organize_id}'");
        return ['errcode' => 0, "data" => ['app' => $model->toArray()]];
    }

    //修改活动配置
    public static function updateapp($request, $response, $rediscli)
    {
        $user_id = $request->getString("user_id");
        $organize_id = $request->getString("organize_id");
        $pfid = $request->getString("pfid");
        if (!isset($user_id) || !isset($organize_id) || !isset($pfid)) {
            return ["errcode" => 401];
        }

        $raw = $request->getRequest()->rawContent();
        $post = json_decode($raw, true);
        if (!isset($post['appid']) || !isset($post['name']) || !isset($post['start_time']) || !isset($post['end_time']) || !isset($post['description']) || !isset($post['img1']) || !isset($post['img2'])) {
            return ["errcode" => 10001];
        }

        if (!isset($post["space"])) {
            return ["errcode" => 10001];
        }

        if (!isset($post["way"])) {
            return ["errcode" => 10001];
        }

        $mysql = Mysql::getInstance("mysql1");
        $mysql->query("start transaction");
        try {
            $appid = $post['appid'];
            $model = new Web3DModel();
            $ok = $model->get("appid = '{$appid}' and organize_id = '{$organize_id}'");
            if (!$ok) {
                throw new \Exception("作品信息不存在");
            }
            $model->name = $post['name'];
            $model->description = $post['description'];
            $model->luck_draw_url = $post['luck_draw_url'] ?? "";
            $model->start_time = $post['start_time'];
            $model->end_time = $post['end_time'];
            $model->img1 = $post['img1'];
            $model->img2 = $post['img2'];
            $ok = $model->save();
            Log::var_dump(["sql" => $model->getLastSql()]);
            if (!$ok) {
                throw new \Exception("err Web3DModel insert sql=" . $model->getLastSql());
            }
            $wid = $model->id;
            $s = new SpaceConfigModel();
            $ok = $s->delete("wid = {$wid}");
            if (!$ok) {
                throw new \Exception("SpaceConfigModel delete fail ");
            }
            $space = $post["space"];
            foreach ($space as $k => $v) {
                $s = new SpaceConfigModel();
                $s->wid = $wid;
                $s->space_id = $v["space_id"];
                $s->name = $v["name"]??"";
                $s->description = $v["description"]??"";
                $s->img = $v["img"]??"";
                $s->status = $v["status"];
                $ok = $s->insert();
                Log::var_dump(["sql" => $model->getLastSql()]);
                if (!$ok) {
                    throw new \Exception("err SpaceConfigModel insert sql =" . $model->getLastSql());
                }
            }

            $model = new WayConfigModel();
            $ok = $model->delete("wid = {$wid}");
            if (!$ok) {
                throw new \Exception("WayConfigModel delete fail ");
            }

            $way = $post["way"];
            foreach ($way as $k => $v) {
                $s = new WayConfigModel();
                $s->wid = $wid;
                $s->sort = $v["sort"];
                $s->space_id = $v["space_id"];
                $ok = $s->insert();
                if (!$ok) {
                    throw new \Exception("err SpaceConfigModel insert sql =" . $model->getLastSql());
                }
            }

            $debug = QYSConfig::get("debug");
            $cookie = $request->getRequest()->header["authorization"];
            if(!$debug){
                $cookie = $request->getRequest()->cookie;
                $cookie = $request->getRequest()->cookie;
                $strs = [];
                foreach ($cookie as $key => $value) {
                    array_push($strs, $key."=".$value);
                }

                $cookie = implode(";", $strs);
            }

            $url = QYSConfig::get("app_url");
            $body = [
                "xappId" => $appid,
                "userId" => $user_id,
                "orgId" => $organize_id,
                "pfid" => $pfid,
                "appTitle" => $post["name"],
                "originAppUrl" => "http://web3dfe.rabbitpre.com/web/index.html",
                "shareDesc" => $post["description"]??"",
                "importType" => 1,
                "subType" => 1,
                "contentType" => "showPage"
            ];
            Log::var_dump(["body" => $body]);
            $res = CoroutineCurl::post($url, "/api/workbench/marketing/xapp/edit", json_encode($body), $cookie);
            if (empty($res)) {
                throw new \Exception("curl xapp edit fail");
            }
            if (!$res["success"]) {
                throw new \Exception("curl xapp success fail");
            }

            $mysql->commit();
        } catch (\Exception $e) {
            $mysql->rollback();
            return ['errcode' => 10009, "errmsg" => $e->getMessage()];
        }

        return ['errcode' => 0];
    }

    //加载app配置
    public static function loadapp($request, $response, $rediscli)
    {
        $appid = $request->getString("appid");
        $model = new Web3DModel();
        $ok = $model->get("appid = '{$appid}'");
        if (!$ok) {
            return ['errcode' => 0, "data" => ['app' => [], "spaces" => [], "ways" => []]];
        }
        $app = $model->toArray();

        $wid = $app["id"];

        $m = new SpaceBaseConfigModel();
        $base = $m->order("id asc")->select();

        $m = new SpaceConfigModel();

        $spaces = $m->where("wid = {$wid}")->select();

        foreach ($spaces as $k => $v) {
            $spaces[$k]['base_name'] = $v["name"];
            $spaces[$k]['name'] = get_name_by_id($v["space_id"], $base);
        }

        $m = new WayConfigModel();
        $ways = $m->where("wid = {$wid}")->select();

        foreach ($ways as $k => $v) {
            $ways[$k]['base_name'] = get_name_by_id($v["space_id"], $base);
        }

        return ['errcode' => 0, "data" => ['app' => $app, "spaces" => $spaces, "ways" => $ways]];
    }

    //加载通用配置
    public static function loadbaseconfig($request, $response, $rediscli)
    {
        $appid = $request->getString("appid");
        $model = new Web3DModel();
        $ok = $model->get("appid = '{$appid}'");
        if (!$ok) {
            return ['errcode' => 0, "data" => ['app' => null, "sponsor" => null, "shares" => null,]];
        }
        $app = $model->toArray();

        $wid = $app["id"];

        $m = new SponsorConfigModel();

        $ok = $m->get("wid = {$wid}");
        $sponsor = [];
        if ($ok) {
            $sponsor = $m->toArray();
        }

        $m = new ShareConfigModel();

        $shares = $m->where("wid = {$wid}")->select();
        return ['errcode' => 0, "data" => ['app' => $app, "sponsor" => $sponsor, "shares" => $shares]];
    }

    //创建通用配置
    public static function createbaseconfig($request, $response, $rediscli)
    {
        $raw = $request->getRequest()->rawContent();
        $post = json_decode($raw, true);
        if (!isset($post['appid']) || !isset($post['name']) || !isset($post['logo']) || !isset($post['description']) || !isset($post['content']) || !isset($post['img']) || !isset($post['is_logo'])) {
            return ["errcode" => 10001];
        }

        if (!isset($post["share"])) {
            return ["errcode" => 10001];
        }


        $appid = $post['appid'];
        $model = new Web3DModel();
        $ok = $model->get("appid = '{$appid}'");
        if (!$ok) {
            return ['errcode' => 10013];
        }
        $wid = $model->id;

        $mysql = Mysql::getInstance("mysql1");
        $mysql->query("start transaction");
        try {

            $model = new SponsorConfigModel();
            $model->wid = $wid;
            $model->name = $post['name'];
            $model->description = $post['description'];
            $model->logo = $post['logo'];
            $model->content = $post['content'];
            $model->img = $post['img'];
            $model->is_logo = $post['is_logo'];
            $ok = $model->insert();
            if (!$ok) {
                throw new \Exception("err SponsorConfigModel insert sql=" . $model->getLastSql());
            }
            $share = $post["share"];
            foreach ($share as $k => $v) {
                $s = new ShareConfigModel();
                $s->wid = $wid;
                $s->space_id = $v["space_id"];
                $s->text = $v["text"];
                $s->img = $v["img"];
                $ok = $s->insert();
                Log::var_dump(["sql" => $model->getLastSql()]);
                if (!$ok) {
                    throw new \Exception("err ShareConfigModel insert sql =" . $model->getLastSql());
                }
            }
            $mysql->commit();
        } catch (\Exception $e) {
            $mysql->rollback();
            Log::var_dump(["Exception" => $e->getMessage()]);
            return ['errcode' => 10009];
        }

        return ['errcode' => 0];
    }

    //修改通用配置
    public static function updatebaseconfig($request, $response, $rediscli)
    {
        $raw = $request->getRequest()->rawContent();
        $post = json_decode($raw, true);
        if (!isset($post['appid']) || !isset($post['name']) || !isset($post['logo']) || !isset($post['description']) || !isset($post['content']) || !isset($post['img']) || !isset($post['is_logo'])) {
            return ["errcode" => 10001];
        }

        if (!isset($post["share"])) {
            return ["errcode" => 10001];
        }

        $appid = $post['appid'];
        $model = new Web3DModel();
        $ok = $model->get("appid = '{$appid}'");
        if (!$ok) {
            return ['errcode' => 10013];
        }
        $wid = $model->id;
        $mysql = Mysql::getInstance("mysql1");
        $mysql->query("start transaction");
        try {

            $model = new SponsorConfigModel();
            $ok = $model->get("wid = {$wid}");
            if (!$ok) {
                throw new \Exception("err SponsorConfigModel get sql=" . $model->getLastSql());
            }
            $model->name = $post['name'];
            $model->description = $post['description'];
            $model->logo = $post['logo'];
            $model->content = $post['content'];
            $model->img = $post['img'];
            $model->is_logo = $post['is_logo'];
            $ok = $model->save();
            if (!$ok) {
                throw new \Exception("err SponsorConfigModel save sql=" . $model->getLastSql());
            }
            $s = new ShareConfigModel();
            $ok = $s->delete("wid = {$wid}");
            if (!$ok) {
                throw new \Exception("ShareConfigModel delete fail ");
            }
            $share = $post["share"];
            foreach ($share as $k => $v) {
                $s = new ShareConfigModel();
                $s->wid = $wid;
                $s->space_id = $v["space_id"];
                $s->text = $v["text"];
                $s->img = $v["img"];
                $ok = $s->insert();
                Log::var_dump(["sql" => $model->getLastSql()]);
                if (!$ok) {
                    throw new \Exception("err ShareConfigModel insert sql =" . $model->getLastSql());
                }
            }
            $mysql->commit();
        } catch (\Exception $e) {
            $mysql->rollback();
            Log::var_dump(["Exception" => $e->getMessage()]);
            return ['errcode' => 10009];
        }

        return ['errcode' => 0];
    }

    //获取公告
    public static function loadnotice($request, $response, $rediscli)
    {
        $appid = $request->getString("appid");
        if (!isset($appid)) {
            return ["errcode" => 10013];
        }
        $model = new Web3DModel();
        $ok = $model->get("appid = '{$appid}'");
        if (!$ok) {
            return ["errcode" => 10013];
        }
        $app = $model->toArray();

        $wid = $app["id"];
        $m = new NoticeConfigModel();

        $notices = $m->where("wid = {$wid}")->select();
        return ['errcode' => 0, "data" => ['app' => $app, "notices" => $notices]];
    }

    //创建公告
    public static function createnotice($request, $response, $rediscli)
    {
        $raw = $request->getRequest()->rawContent();
        $post = json_decode($raw, true);
        if (!isset($post['appid']) || !isset($post['name']) || !isset($post['start_time']) || !isset($post['end_time']) || !isset($post['content'])) {
            Log::var_dump(["len" => 438]);
            return ["errcode" => 10001];
        }
        $appid = $post['appid'];
        $model = new Web3DModel();
        $ok = $model->get("appid = '{$appid}'");
        if (!$ok) {
            Log::var_dump(["len" => 445]);
            return ['errcode' => 10013];
        }
        $wid = $model->id;

        $model = new NoticeConfigModel();
        $model->wid = $wid;
        $model->name = $post['name'];
        $model->start_time = $post['start_time'];
        $model->end_time = $post['end_time'];
        $model->content = $post['content'];
        $ok = $model->insert();
        if (!$ok) {
            return ['errcode' => 10009];
        }

        return ['errcode' => 0];
    }

    //编辑公告
    public static function updatenotice($request, $response, $rediscli)
    {
        $raw = $request->getRequest()->rawContent();
        $post = json_decode($raw, true);
        if (!isset($post['id']) || !isset($post['appid']) || !isset($post['name']) || !isset($post['start_time']) || !isset($post['end_time']) || !isset($post['content'])) {
            return ["errcode" => 10001];
        }
        $appid = $post['appid'];
        $model = new Web3DModel();
        $ok = $model->get("appid = '{$appid}'");
        if (!$ok) {
            return ['errcode' => 10013];
        }
        $wid = $model->id;
        $model = new NoticeConfigModel();
        $ok = $model->get("wid = {$wid} and id = {$post['id']}");
        if (!$ok) {
            return ['errcode' => 10001];
        }
        $model->name = $post['name'];
        $model->start_time = $post['start_time'];
        $model->end_time = $post['end_time'];
        $model->content = $post['content'];
        $ok = $model->save();
        if (!$ok) {
            return ['errcode' => 10009];
        }

        return ['errcode' => 0];
    }

    public static function deletenotice($request, $response, $rediscli)
    {
        $raw = $request->getRequest()->rawContent();
        $post = json_decode($raw, true);
        if (!isset($post['id']) || !isset($post['appid'])) {
            return ["errcode" => 10001];
        }
        $appid = $post['appid'];
        $model = new Web3DModel();
        $ok = $model->get("appid = '{$appid}'");
        if (!$ok) {
            return ['errcode' => 10013];
        }
        $wid = $model->id;

        $model = new NoticeConfigModel();
        $ok = $model->where("wid = {$wid} and id = {$post['id']}")->delete();
        if (!$ok) {
            return ['errcode' => 10009];
        }

        return ['errcode' => 0];
    }


    public static function updatestatus($request, $response, $rediscli)
    {
        $raw = $request->getRequest()->rawContent();
        $post = json_decode($raw, true);
        if (!isset($post['id']) || !isset($post['appid']) || !isset($post['status'])) {
            return ["errcode" => 10001];
        }
        $appid = $post['appid'];
        $model = new Web3DModel();
        $ok = $model->get("appid = '{$appid}'");
        if (!$ok) {
            return ['errcode' => 10013];
        }
        $wid = $model->id;
        $model = new NoticeConfigModel();
        $ok = $model->get("wid = {$wid} and id = {$post['id']}");
        if (!$ok) {
            return ['errcode' => 10001];
        }
        $model->status = $post['status'];
        $ok = $model->save();
        if (!$ok) {
            return ['errcode' => 10009];
        }

        return ['errcode' => 0];
    }


    //获取公告
    public static function loadhallconfig($request, $response, $rediscli)
    {
        $appid = $request->getString("appid");
        if (!isset($appid)) {
            return ["errcode" => 10013];
        }
        $model = new Web3DModel();
        $ok = $model->get("appid = '{$appid}'");
        if (!$ok) {
            return ["errcode" => 10013];
        }
        $app = $model->toArray();

        $wid = $app["id"];
        $m = new HallConfigModel();

        $ok = $m->get("wid = '{$wid}'");
        $hall = [];
        if ($ok) {
            $hall = $m->toArray();
        }
        return ['errcode' => 0, "data" => ["app" => $app, "hall" => $hall]];
    }

    //广场大厅配置
    public static function createhallconfig($request, $response, $rediscli)
    {
        $raw = $request->getRequest()->rawContent();
        $post = json_decode($raw, true);
        if (!isset($post['appid'])) {
            return ['errcode' => 10013];
        }
        if (!isset($post['tp']) || !isset($post['url']) || !isset($post['img'])) {
            return ["errcode" => 10001];
        }

        $appid = $post['appid'];
        $model = new Web3DModel();
        $ok = $model->get("appid = '{$appid}'");
        if (!$ok) {
            return ['errcode' => 10013];
        }
        $wid = $model->id;
        $model = new HallConfigModel();
        $model->wid = $wid;
        $model->tp = $post['tp'];
        $model->url = $post['url'];
        $model->img = $post['img'];
        $ok = $model->insert();
        if (!$ok) {
            return ['errcode' => 10009];
        }
        return ['errcode' => 0];
    }

    //修改广场大厅配置
    public static function updatehallconfig($request, $response, $rediscli)
    {
        $raw = $request->getRequest()->rawContent();
        $post = json_decode($raw, true);
        if (!isset($post['appid'])) {
            return ['errcode' => 10013];
        }
        if (!isset($post['id']) || !isset($post['tp']) || !isset($post['url']) || !isset($post['img'])) {
            return ["errcode" => 10001];
        }
        $appid = $post['appid'];
        $model = new Web3DModel();
        $ok = $model->get("appid = '{$appid}'");
        if (!$ok) {
            return ['errcode' => 10013];
        }
        $wid = $model->id;
        $model = new HallConfigModel();
        $ok = $model->get("wid = {$wid}");
        if (!$ok) {
            return ['errcode' => 10001];
        }
        $model->tp = $post['tp'];
        $model->url = $post['url'];
        $model->img = $post['img'];
        $ok = $model->save();
        if (!$ok) {
            return ['errcode' => 10009];
        }
        return ['errcode' => 0];
    }


    //获取展厅配置adv
    public static function loadadvconfig($request, $response, $rediscli)
    {
        $appid = $request->getString("appid");
        $space_id = $request->getString("space_id");
        if (!isset($appid) || !isset($space_id)) {
            return ["errcode" => 10001];
        }
        $model = new Web3DModel();
        $ok = $model->get("appid = '{$appid}'");
        if (!$ok) {
            return ["errcode" => 10013];
        }
        $app = $model->toArray();

        $wid = $app["id"];
        $model = new AdvModel();
        $advs = $model->where("wid = {$wid} and space_id = {$space_id}")->order("pos asc")->select();
        foreach ($advs as $k => $v) {
            $model = new AdvChildModel();
            $childs = $model->where("aid = {$v['id']}")->select();
            $advs[$k]['childs'] = $childs;
        }
        return ['errcode' => 0, "data" => ["app" => $app, "advs" => $advs]];
    }

    //展厅配置adv
    public static function createadvconfig($request, $response, $rediscli)
    {
        $raw = $request->getRequest()->rawContent();
        $post = json_decode($raw, true);
        if (!isset($post['appid']) || !isset($post['space_id']) || !isset($post['advs'])) {
            return ["errcode" => 10001];
        }

        $space_id = $post['space_id'];

        if ($space_id != 2 && $space_id != 4 && $space_id != 5) {
            return ["errcode" => 10001];
        }

        $appid = $post['appid'];
        $model = new Web3DModel();
        $ok = $model->get("appid = '{$appid}'");
        if (!$ok) {
            return ['errcode' => 10013];
        }
        $wid = $model->id;

        $advs = $post['advs'];
        $mysql = Mysql::getInstance("mysql1");
        $mysql->query("start transaction");
        try {
            foreach ($advs as $k => $v) {
                $model = new AdvModel();
                $model->wid = $wid;
                $model->space_id = $space_id;
                $model->pos = $v['pos'];
                $model->tp = $v['tp'];
                $model->name = $v['name'];
                $model->description = $v['description'];
                $model->img = $v['img'];
                $model->size = $v['size'];
                $ok = $model->insert();
                if (!$ok) {
                    throw new \Exception("err AdvModel insert sql =" . $model->getLastSql());
                }
                $aid = $model->id;
                $childs = $v["childs"];
                foreach ($childs as $key => $value) {
                    $model = new AdvChildModel();
                    $model->aid = $aid;
                    $model->url = $value['url'];
                    $ok = $model->insert();
                    if (!$ok) {
                        throw new \Exception("err AdvChildModel insert sql =" . $model->getLastSql());
                    }
                }
            }
            $mysql->commit();
        } catch (\Exception $e) {
            $mysql->rollback();
            Log::var_dump(["Exception" => $e->getMessage()]);
            return ['errcode' => 10009];
        }

        return ['errcode' => 0];
    }



    //展厅配置adv
    public static function updateadvconfig($request, $response, $rediscli)
    {
        $raw = $request->getRequest()->rawContent();
        $post = json_decode($raw, true);
        if (!isset($post['appid']) || !isset($post['space_id']) || !isset($post['advs'])) {
            return ["errcode" => 10001];
        }
        $space_id = $post['space_id'];

        $appid = $post['appid'];
        $model = new Web3DModel();
        $ok = $model->get("appid = '{$appid}'");
        if (!$ok) {
            return ['errcode' => 10013];
        }
        $wid = $model->id;

        $advs = $post['advs'];
        $mysql = Mysql::getInstance("mysql1");
        $mysql->query("start transaction");
        try {
            foreach ($advs as $k => $v) {
                $model = new AdvModel();
                $ok = $model->get("wid = {$wid} and space_id = {$space_id} and id = {$v['id']}");
                if (!$ok) {
                    throw new \Exception("AdvModel not found ID = " . $v["id"]);
                }
                $model->tp = $v['tp'];
                $model->name = $v['name'];
                $model->description = $v['description'];
                $model->img = $v['img'];
                $model->size = $v['size'];
                $ok = $model->save();
                if (!$ok) {
                    throw new \Exception("err AdvModel save sql =" . $model->getLastSql());
                }
                $aid = $model->id;
                $model = new AdvChildModel();
                $ok = $model->delete("aid = {$aid}");
                if (!$ok) {
                    throw new \Exception("AdvChildModel delete fail");
                }

                $childs = $v["childs"];
                foreach ($childs as $key => $value) {
                    $model = new AdvChildModel();
                    $model->aid = $aid;
                    $model->url = $value['url'];
                    $ok = $model->insert();
                    if (!$ok) {
                        throw new \Exception("err AdvChildModel insert sql =" . $model->getLastSql());
                    }
                }
            }
            $mysql->commit();
        } catch (\Exception $e) {
            $mysql->rollback();
            Log::var_dump(["Exception" => $e->getMessage()]);
            return ['errcode' => 10009];
        }

        return ['errcode' => 0];
    }

    //获取展厅配置adv
    public static function loadgameconfig($request, $response, $rediscli)
    {
        $appid = $request->getString("appid");
        if (!isset($appid)) {
            return ["errcode" => 10001];
        }
        $model = new Web3DModel();
        $ok = $model->get("appid = '{$appid}'");
        if (!$ok) {
            return ["errcode" => 10013];
        }
        $app = $model->toArray();

        $wid = $app["id"];
        $model = new GameConfigModel();
        $game = $model->where("wid = {$wid}")->order("pos asc")->select();
        return ['errcode' => 0, "data" => ["app" => $app, "game" => $game]];
    }

    //互动休闲区创建
    public static function creategameconfig($request, $response, $rediscli)
    {
        $raw = $request->getRequest()->rawContent();
        $post = json_decode($raw, true);
        if (!isset($post['appid']) || !isset($post['space_id']) || !isset($post['games'])) {
            return ["errcode" => 10001];
        }

        $space_id = $post['space_id'];

        if ($space_id != 3) {
            return ["errcode" => 10001];
        }

        $appid = $post['appid'];
        $model = new Web3DModel();
        $ok = $model->get("appid = '{$appid}'");
        if (!$ok) {
            return ['errcode' => 10013];
        }
        $wid = $model->id;

        $games = $post['games'];
        $mysql = Mysql::getInstance("mysql1");
        $mysql->query("start transaction");
        try {
            foreach ($games as $k => $v) {
                $model = new GameConfigModel();
                $model->wid = $wid;
                $model->space_id = $space_id;
                $model->pos = $v['pos'];
                $model->title = $v['title'];
                $model->notice = $v['notice'];
                $model->url = $v['url'];
                $model->img = $v['img'];
                $model->size = $v['size'];
                $ok = $model->insert();
                if (!$ok) {
                    throw new \Exception("err GameConfigModel insert sql =" . $model->getLastSql());
                }
            }
            $mysql->commit();
        } catch (\Exception $e) {
            $mysql->rollback();
            Log::var_dump(["Exception" => $e->getMessage()]);
            return ['errcode' => 10009];
        }

        return ['errcode' => 0];
    }



    //互动休闲区修改
    public static function updategameconfig($request, $response, $rediscli)
    {
        $raw = $request->getRequest()->rawContent();
        $post = json_decode($raw, true);
        if (!isset($post['appid']) || !isset($post['space_id']) || !isset($post['games'])) {
            Log::var_dump($post);
            return ["errcode" => 10001];
        }

        $space_id = $post['space_id'];

        if ($space_id != 3) {
            Log::var_dump($space_id);
            return ["errcode" => 10001];
        }

        $appid = $post['appid'];
        $model = new Web3DModel();
        $ok = $model->get("appid = '{$appid}'");
        if (!$ok) {
            Log::var_dump($appid);
            return ['errcode' => 10013];
        }
        $wid = $model->id;
        $games = $post['games'];
        $mysql = Mysql::getInstance("mysql1");
        $mysql->query("start transaction");
        try {
            $model = new GameConfigModel();
            $ok = $model->delete("wid = {$wid}");
            if (!$ok) {
                throw new \Exception("GameConfigModel delete fail ");
            }
            foreach ($games as $k => $v) {
                $model = new GameConfigModel();
                $model->wid = $wid;
                $model->space_id = $space_id;
                $model->pos = $v['pos'];
                $model->title = $v['title'];
                $model->notice = $v['notice'];
                $model->url = $v['url'];
                $model->img = $v['img'];
                $model->size = $v['size'];
                $ok = $model->insert();
                if (!$ok) {
                    throw new \Exception("err GameConfigModel insert sql =" . $model->getLastSql());
                }
            }
            $mysql->commit();
        } catch (\Exception $e) {
            $mysql->rollback();
            Log::var_dump(["Exception" => $e->getMessage()]);
            return ['errcode' => 10009];
        }

        return ['errcode' => 0];
    }


    //微信分享设置
    public static function wxshareconfig($request, $response, $rediscli)
    {
        $raw = $request->getRequest()->rawContent();
        $post = json_decode($raw, true);
        if (!isset($post['appid']) || !isset($post['wx_share_title']) || !isset($post['wx_share_desc']) || !isset($post['wx_share_icon'])) {
            return ["errcode" => 10001];
        }

        $appid = $post['appid'];
        $model = new Web3DModel();
        $ok = $model->get("appid = '{$appid}'");
        if (!$ok) {
            return ['errcode' => 10013];
        }
        $wid = $model->id;
        $model->wx_share_title = $post['wx_share_title'];
        $model->wx_share_desc = $post['wx_share_desc'];
        $model->wx_share_icon = $post['wx_share_icon'];
        $ok = $model->save();
        if (!$ok) {
            return ['errcode' => 10009];
        }

        return ['errcode' => 0];
    }


    public static function loadmsg($request, $response, $rediscli)
    {
        $appid = $request->getString("appid");
        if (!isset($appid)) {
            return ["errcode" => 10013];
        }
        $model = new Web3DModel();
        $ok = $model->get("appid = '{$appid}'");
        if (!$ok) {
            return ["errcode" => 10013];
        }
        $app = $model->toArray();

        $wid = $app["id"];
        $m = new MsgModel();

        $msgs = $m->where("wid = {$wid}")->select();
        return ['errcode' => 0, "data" => ['app' => $app, "msgs" => $msgs]];
    }


    public static function createmsg($request, $response, $rediscli)
    {
        $raw = $request->getRequest()->rawContent();
        $post = json_decode($raw, true);
        if (!isset($post['appid']) || !isset($post['msg'])) {
            return ["errcode" => 10001];
        }
        $appid = $post['appid'];
        $model = new Web3DModel();
        $ok = $model->get("appid = '{$appid}'");
        if (!$ok) {
            return ['errcode' => 10013];
        }
        $wid = $model->id;
        $model = new MsgModel();
        $model->wid = $wid;
        $model->msg = $post['msg'];
        $ok = $model->insert();
        if (!$ok) {
            return ['errcode' => 10009];
        }

        return ['errcode' => 0];
    }

    public static function updatemsg($request, $response, $rediscli)
    {
        $raw = $request->getRequest()->rawContent();
        $post = json_decode($raw, true);
        if (!isset($post['appid']) || !isset($post['id']) || !isset($post['msg'])) {
            return ["errcode" => 10001];
        }
        $appid = $post['appid'];
        $model = new Web3DModel();
        $ok = $model->get("appid = '{$appid}'");
        if (!$ok) {
            return ['errcode' => 10013];
        }
        $wid = $model->id;

        $model = new MsgModel();

        $ok = $model->get("wid = {$wid}");
        if (!$ok) {
            return ["errcode" => 10001];
        }
        $model->msg = $post['msg'];
        $ok = $model->save();
        if (!$ok) {
            return ['errcode' => 10009];
        }

        return ['errcode' => 0];
    }

    public static function deletemsg($request, $response, $rediscli)
    {
        $raw = $request->getRequest()->rawContent();
        $post = json_decode($raw, true);
        if (!isset($post['appid']) || !isset($post['id'])) {
            return ["errcode" => 10001];
        }
        $appid = $post['appid'];
        $model = new Web3DModel();
        $ok = $model->get("appid = '{$appid}'");
        if (!$ok) {
            return ['errcode' => 10013];
        }
        $wid = $model->id;
        $model = new MsgModel();
        $ok = $model->where("wid = {$wid} and id = {$post['id']}")->delete();
        if (!$ok) {
            return ["errcode" => 10009];
        }
        return ['errcode' => 0];
    }


    public static function loadmsglog($request, $response, $rediscli)
    {
        $raw = $request->getRequest()->rawContent();
        $post = json_decode($raw, true);
        if (!isset($post['appid'])) {
            return ["errcode" => 10001];
        }
        $page = !isset($post['page']) ?? 1;
        $limit = !isset($post['limit']) ?? 8;
        $appid = $post['appid'];
        $model = new Web3DModel();
        $ok = $model->get("appid = '{$appid}'");
        if (!$ok) {
            return ['errcode' => 10013];
        }
        $wid = $model->id;
        $model = new MsgLogModel();
        $msgs = $model->where("wid = {$wid} and deleted_at = ''")->page($page)->limit($limit)->order("created_at desc")->select();
        Log::var_dump(["sql" => $model->getLastSql()]);
        return ['errcode' => 0, "data" => ['msgs' => $msgs]];
    }


    public static function deletemsglog($request, $response, $rediscli)
    {
        $raw = $request->getRequest()->rawContent();
        $post = json_decode($raw, true);
        if (!isset($post['appid']) || !isset($post['id'])) {
            return ["errcode" => 10001];
        }

        $appid = $post['appid'];
        $model = new Web3DModel();
        $ok = $model->get("appid = '{$appid}'");
        if (!$ok) {
            return ['errcode' => 10013];
        }
        $wid = $model->id;

        $model = new MsgLogModel();
        $ok = $model->where("wid = {$wid} and id = {$post['id']}")->del();
        if (!$ok) {
            return ["errcode" => 10009];
        }
        return ['errcode' => 0];
    }
}

class AdminCtrl
{
    public function invoke($request, $response, $params)
    {
        $response->addHeader("Content-Type", 'application/json');
        $response->addHeader("Access-Control-Allow-Origin", "*");
        $response->addHeader("Access-Control-Allow-Methods", 'POST, GET, OPTIONS, DELETE');
        $response->addHeader('Access-Control-Allow-Headers', "Origin, X-Requested-With, Content-Type, Accept");
        $response->sendHttpHeader();
        $fname = $params['fname'];
        $rediscli = Redis::getInstance("redis1");
        $result = null;
        $result = CMDADMIN::$fname($request, $response, $rediscli);
        if (isset($result['errcode']) && $result['errcode'] != 0) {
            $errcode = $result['errcode'];
            if (!isset($result['errmsg'])) {
                $result['errmsg'] = Config::get('errmsg', 'e' . $errcode);
            }
        }
        Log::info('debug', $request, ['fname' => $fname, 'result' => $result]);
        $response->say(json_encode($result));
    }
}
